#!/usr/bin/python
import signal
import urllib
import time
import atexit
import sys
import os
import time, datetime

import fetch, character, pickle, util

def cleanup(thread):
    print "atexit cleanup() called"
    thread.kill()
    sys.exit(0)

def main():
    config = pickle.ConfigPickle()
    apikey = ""
    userid = ""
    characterid = ""

    try:
        config.loadData()
    except IOError, (errno, strerror):
        if errno is 2: # File not found
            print "Please enter your character data for Eve Online: "
            userid = raw_input("User ID: ")
            apikey = raw_input("API key: ")
            characterid = raw_input("Character ID: ")
            config.setAccount(userid, apikey, [characterid])
            config.saveData()
        else:
            print "Unhandled config pickle error."
            sys.exit(1)
    userid = config.uids()[0] # grab the first uid
    characterid = config.chars(userid)[0] # grab the first char

    # PoolThread(num threads, update interval)
    FETCH_PREFIX = os.getcwd()
    pool = fetch.PoolThread(FETCH_PREFIX, 2, 20)

    # Cleanup properly on kill and program exit
    atexit.register(cleanup, pool)
    signal.signal(signal.SIGTERM, lambda signum, stack_frame: sys.exit(1))
    signal.signal(signal.SIGINT, lambda signum, stack_frame: sys.exit(1))

    pool.start()

    # Yoink stuff from the pickle
    try:
        params = config.getCharParams(userid, characterid)
    except Exception, strerr:
        print strerr
        sys.exit(1)


    print "Using char data ", params, "\n"


    eve = {
            "SkillTree": "/eve/SkillTree.xml.aspx",
    }
    char = {
            "CharacterSheet": "/char/CharacterSheet.xml.aspx",
            "SkillInTraining": "/char/SkillInTraining.xml.aspx",
    }

    print "push"
    pool.pushURL(eve["SkillTree"])
    pool.pushURL(char["CharacterSheet"], params, fetch_now=True)
    pool.pushURL(char["SkillInTraining"], params, fetch.
        FETCH_PERIODIC)

    # Build up skill tree
    pool.wait(eve["SkillTree"])
    stree = character.SkillTree(util.xmlpath(FETCH_PREFIX,
        eve["SkillTree"]))
    print "Skill tree loaded."

    pool.wait(char["CharacterSheet"])
    try:
        mychar = character.Character(util.xmlpath(
            FETCH_PREFIX, char["CharacterSheet"], params))
    except Exception, errmsg:
        raise
        sys.exit(-1)
    print "Character loaded."
    while True:
        pool.wait(char["SkillInTraining"])
        try:
            mychar.parseSIT(util.xmlpath(
                FETCH_PREFIX, char["SkillInTraining"], params))
        except Exception, errmsg:
            raise
            sys.exit(-1)

        sit = mychar.skillInTraining

        sit_name = stree.types[sit.trainingTypeID].typeName

        level = sit.trainingToLevel

        end_dt = util.eve2local(sit.trainingEndTime)
        end_s = end_dt.strftime("%a, %b %d at %I:%M %p")

        eta_s = util.eta_str(end_dt)

        start_sp, end_sp = sit.trainingStartSP, sit.trainingDestinationSP
        print
        print """Currently training skill "%s" to level %s, scheduled to finish in %s on %s.""" % (sit_name, level, eta_s, end_s)


if __name__ == "__main__":
    main()
